package com.youku.expression.ast;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.youku.expression.Token;
import com.youku.expression.TokenType;
import com.youku.expression.environment.Environment;

/**
 * 抽象语法树
 * 
 * @author loda
 *
 */
public abstract class Ast {

	protected Token token;

	// 子节点
	protected List<Ast> children = new ArrayList<>();

	// 父节点
	protected Ast parent;

	public Ast() {
		super();
	}

	public Ast(Ast... asts) {
		this(Arrays.asList(asts));
	}

	public Ast(List<Ast> asts) {
		for (Ast ast : asts) {
			children.add(ast);
		}
		parent = this;
	}

	public Ast(Token token, Ast... asts) {
		this(asts);
		this.token = token;
	}

	public abstract Object eval(Environment environment);

	public void setToken(Token token) {
		this.token = token;
	}

	public void addChild(Ast ast) {
		children.add(ast);
	}

	public Ast getChild(int i) {
		return children.get(i);
	}

	public Ast getLastChild() {
		return children.get(childSize() - 1);
	}

	public String getTokenValue() {
		return token.value();
	}

	public TokenType getTokenType() {
		return token.tokenType();
	}

	public int childSize() {
		return children.size();
	}

	public Token getToken() {
		return token;
	}

	public List<Ast> children() {
		return children;
	}

	public Ast parent() {
		return parent;
	}

	@Override
	public String toString() {
		return token.value();
	}
}
